package com.ClothingStorePOS.controller;


import com.ClothingStorePOS.pojo.*;
import com.ClothingStorePOS.services.IUserService;
import com.ClothingStorePOS.services.IRoleService;
import com.ClothingStorePOS.shiro.ShiroMD5;
import com.ClothingStorePOS.shiro.ShiroUser;
import com.ClothingStorePOS.shiro.ShiroUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.DisabledAccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;

@Controller
@RequestMapping("/user")
public class UserController {
	@Resource(name="userService")
	private IUserService userService;
	@Resource(name="roleService")
	private IRoleService roleService;

	//添加用户
	@RequiresPermissions("user:addUser")
	@RequestMapping("/addUser")
    public ModelAndView addUserOne(User user,Integer rid,HttpServletRequest request){
		ModelAndView mv = new ModelAndView();
		//对密码进行加密
		ShiroMD5 shiroMD5 = new ShiroMD5();
		String newMd5Password = shiroMD5.GetPwd(user.getLoginname(),user.getPassword());
		user.setPassword(newMd5Password);
		int result = userService.addUser(user);
		roleService.addUserRole(user.getId(),rid);

		System.out.println(result);
		mv.addObject("result",result);
		mv.setViewName("/addUser");
		if (result==1)
			request.setAttribute("addUserSucceed","添加用户成功！");
		else
			request.setAttribute("addUserError","添加成功失败！");
		return mv;
    }

	@RequestMapping("/login")
	@ResponseBody
	public Result loginPost(String username, String txtCode,String password,HttpSession session) {

		Result result = new Result();
		// 比对验证码是否正确
		if ( !(txtCode.equals(session.getAttribute("code") ) ) ) {
			result.setMsg("验证码错误");
			return result;
		}
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token =
				new UsernamePasswordToken(username, password);
//        token.setRememberMe(true);
		try {
			user.login(token);
		} catch (UnknownAccountException e) {
			result.setMsg("账号不存在");
			return result;
		} catch (DisabledAccountException e) {
			result.setMsg("账号未启用");
			return result;
		} catch (IncorrectCredentialsException e) {
			result.setMsg("密码错误");
			return result;
		} catch (RuntimeException e) {
			result.setMsg("未知错误,请刷新界面重新登录！"+e.getMessage());
			System.out.println(e.getMessage());
//            result.setMsg(e.getMessage());
			return result;
		}

		result.setSuccess(true);
/*		session.setAttribute("currUser", user);*/
		System.out.println(user.getPrincipal());
		return result;

/*User user = userService.findUserByLoginName(username);
System.out.println(user.getLoginname());
if (user.getPassword().equals(password)) {
	result.setSuccess(true);
	session.setAttribute("currUser", user);
	return result;
}else{
	result.setMsg("登录失败");
}
return result;*/
	}

	/**
	 * 退出
	 *
	 * @return
	 */
	@RequestMapping("/logout")
//    @ResponseBody
	public String logout() {
		ShiroUtils.logout();
		return "redirect:/index.jsp" ;
	}

	//查找用户信息
	@RequiresPermissions("user:find")
	@RequestMapping("/find")
	@ResponseBody
	public Object findUserByRoleId(HttpServletRequest request){

		ShiroUser shiroUser = (ShiroUser) SecurityUtils.getSubject().getPrincipal();
		//当前页数
		int page = Integer.parseInt(request.getParameter("page"));
		System.out.println("当前页数"+page);
		//每页显示条数
		int limit = Integer.parseInt(request.getParameter("limit"));
		System.out.println("每页显示条数"+limit);

		int start = limit*(page-1);

		int counts = 0;

		Map userMap = new HashMap();
		List<UserVO> userVOList = new ArrayList<>();
		List<User> userList = new ArrayList<>();
		for (int roleId:shiroUser.roleList){
			if(roleId==1){
			 userList = this.userService.findUserByRoleId(2,start,limit);
			 counts = this.userService.userCountsSale(2);
				break;
			}else if (roleId==3){
				userList = this.userService.findAllUserByRoleId(1,2,start,limit);
				counts = this.userService.userCountsSaleAndManager(1,2);
			}

		}

		for (User user:userList){
			UserVO userVO = new UserVO(user.getId(),user.getLoginname(),user.getName(),user.getPassword(),user.getSex(),
					user.getAge(),user.getCreatedate(),user.getPhone());
			for (Role role:user.getRoleList()){
				userVO.setRoleId(role.getId());
				userVO.setRoleName(role.getRole());
			}
			userVOList.add(userVO);
		}

		//按照layui的格式存储数据
		userMap.put("code", 0);
		userMap.put("msg", "");
		userMap.put("count", counts);
		userMap.put("data", userVOList);

			//转化为json格式
			JSONObject jsonObject = JSONObject.parseObject(JSONObject.toJSONString(userMap));
			return jsonObject;
		}

		//删除用户
		@RequiresPermissions("user:delete")
		@RequestMapping("/delete")
		@ResponseBody
		public int deleteByUserId(int id){
		return this.userService.deleteByUserId(id);
		}


		//验证用户是否已经存在
		@RequestMapping("/findByLoginName")
		@ResponseBody
		public Boolean findByLoginName(String loginname){

		User existUser = this.userService.findUserByLoginName(loginname);
		if (existUser==null)
			return true;
		else
			return false;
/*			HttpServletRequest request = ServletActionContext.getRequest();
			HttpServletResponse response = ServletActionContext.getResponse();
			String loginname = request.getParameter("loginname").trim();

			response.setContentType("text/html");
			User existUser=userService.findUserByLoginName(loginname);//完成数据库验证
			String value=null;
			//特别注意，用户不存在，写出“true"
			if(existUser==null){
				value="true";
			}else value="false";//特别注意，用户存在，写出“false"
			try {
				response.getWriter().write(value);
			} catch (IOException e) {
				e.printStackTrace();
			}*/

		}

		@RequiresPermissions("user:toAlterUserPage")
	@RequestMapping("/toAlterUserPage")
	public String toAlterUserPage(Integer id, HttpServletRequest request){

		User user = this.userService.selectUserById(id);

		UserVO userVO = new UserVO(user.getId(),user.getLoginname(),user.getName(),user.getPassword(),user.getSex(),
				user.getAge(),user.getCreatedate(),user.getPhone());
		for (Role role:user.getRoleList()){
			userVO.setRoleId(role.getId());
			userVO.setRoleName(role.getRole());
		}
		System.out.println("roleId为："+userVO.getRoleId());
		request.setAttribute("UserVoMsg",userVO);
		return "/alterUser";
	}

	@RequiresPermissions("user:editUser")
	@RequestMapping(value = "/editUser",method = RequestMethod.POST)
	@ResponseBody
	public Result editUser(UserVO userVO){
		System.out.println("UserVO的id为"+userVO.getId());
		Result result = new Result();
		 int a = this.userService.editUser(userVO);
		 if (a>=1){
		 	result.setSuccess(true);
		 }else
		 	result.setSuccess(false);
		 return result;
	}


}
